//index.js
const app = getApp()
const ClientApi = app.ClientApi
const clientGet = app.clientGet
const {Stomp} = require('../../utils/stomp.min.js');
import CommandType from '../../enum/command-type'
import config from '../../env/index'
import { setItem, clear, getItem  } from '../../utils/store'
Page({
  data: {
    active: 0,
    steps: [
      {
        text: '订单确认',
      },
      {
        text: '车型测量',
      },
      {
        text: '车型确认',
      },
      {
        text: '装车进行',
      },
      {
        text: '装车结果',
      },
    ],
    faultMessage: '', // 错误信息
    isFault: false, // 是否故障
    overload: {},
    car: {}, // 车辆信息
    orderData: {}, // 订单信息
    material: {}, // 物料信息
    CommandType, // 事件消息类型
    stomClient:null, // 客户端
    socketOpen:false,//用于标识websocket是否已经打开
    destination:'/topic/url',//当前订阅的主题
    loadingCount: {}, // 每一包的数据
    commandStatus: 'NOTIFY_COMMAND_ORDER_WAIT', // 默认是等待启动状态
    subscribe:null,//当前已经订阅的主题对象，用于退出时，注销监听
  },
  handleActiveChange(e) {
    this.setData({active: e.detail})
  },
  // 获取物料列表
  async getTrueWuMessage() {
    const factoryId = getItem("factoryId")
    const materials = await clientGet(`${ClientApi.getMaterialList}/factoryId/${factoryId}`)
    return materials
  },
  async getlaneStatusById() {
    const laneId = getItem('laneId')
    const factoryId = getItem("factoryId")
    const laneStatusRes = await clientGet(`${ClientApi.getLaneStatusById}/factoryId/${factoryId}/laneId/${laneId}`)
    const command = laneStatusRes[0].command
    this.setData({
      commandStatus: command
    })
  },
  getCarData(e) {
    const carInfo = e.detail;
    this.setData({
      car: carInfo
    })
  },
  // 获取订单数据
  async getOrderData(e) {
    const orderDetail = e.detail
    this.setData({
      orderData: orderDetail
    })
    const materials = await this.getTrueWuMessage()
    const currentMaterial = materials.find((material) => {
      return material.id === orderDetail.materialId
    })
    this.setData({
      material: currentMaterial
    })
  },
  initWebsocket(id) {
    Stomp.setInterval = function (interval, f) {
      return setInterval(f, interval);
    };
    Stomp.clearInterval = function (id) {
      return clearInterval(id);
    };
    const socketMsgQueue = []
    const _this = this
    function sendSocketMessage(msg) {
      if (_this.data.socketOpen) {
        wx.sendSocketMessage({
          data: msg
        })
      } else {
        socketMsgQueue.push(msg)
      }
    }
    const ws = {
      send: sendSocketMessage,
      onopen: null,
      onmessage: null
    }
    const factoryId = getItem("factoryId")
    const socketTask=wx.connectSocket({
      url: `${config.Dev.wsUrl}/factoryId/${factoryId}/laneId/${id}`,
      header:{
        'content-type': 'application/json'
      },
      fail:res=>{
        console.log(res)
      }
    })
    socketTask.onOpen(() => {
      console.log('websocket链接已打开guozhaoxi')
      this.setData({socketOpen:true},()=>{
        ws.onopen && ws.onopen()
      })
    })
    socketTask.onClose(() => {
      console.log('websocket已关闭')
      this.setData({
        socketOpen: false
      })
    })
    socketTask.onMessage(function (res) {
      ws.onmessage && ws.onmessage(res)
    })
    const client = Stomp.over(ws);
    client.connect({name:'xcx_user'},  () => {
      const subscribe= client.subscribe(`${this.data.destination}/${id}`, msg=> {
        const message=JSON.parse(msg.body)
        console.log('message',message)
        let commandStatus = message.command
        let messageObj = message.message
        if (commandStatus === CommandType.NOTIFY_COMMAND_STACK_CALCULATION) {
          let max = messageObj[1]
          let current = messageObj[0]
          this.setData({
            overload: {
              max,
              current
            }
          })
        }
        if (commandStatus === CommandType.NOTIFY_COMMAND_LOADING_FAULT) {
          this.setData({
            isFault: true,
            faultMessage: messageObj[0].description
          })
        }
        this.setData({
          loadingCount: messageObj,
          commandStatus
        })
      });
      this.setData({
        subscribe,
      })
    })
    this.setData({stomClient:client})
  },
  // 页面加载完的生命周期函数
  onLoad: async function (option) {
    const id = option.id
    this.initWebsocket(id)
    await this.getlaneStatusById()
  },
    /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clear("taiList")
    if (this.data.socketOpen) {
      if(this.data.subscribe){
        this.data.subscribe.unsubscribe()
      }
      wx.closeSocket()
    }
  },
})
